package com.cool4j.generator.util;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.Map;

/**
 * 模板操作工具类
 *
 * @author Frank create on 16/1/8 22:06
 */
@SuppressWarnings("unused")
public class VelocityUtil {

    public static void generatorCode(String templateFile, Map contextMap, String path, String fileName) {
        // 设置模板载入路径
        VelocityContext context = new VelocityContext();
        // 获取模板引擎
        VelocityEngine engine = new VelocityEngine();
        // 模板文件所在的路径
        String templatePath = System.getProperty("user.dir") + "\\template";
        // 设置参数
        engine.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templatePath);
        // 处理中文问题
        engine.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
        engine.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        // 初始化模板
        engine.init();

        // 设置变量值
        for (Object key : contextMap.keySet()) {
            context.put(key.toString(), contextMap.get(key));
        }

        Template template = null;
        try {
            template = engine.getTemplate(templateFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        StringWriter writer = new StringWriter();
        if (template != null) {
            template.merge(context, writer);
        }

        // 生成目录
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        writeFile(folder + "/" + fileName, writer.toString());
    }

    /**
     * 写入文件
     *
     * @param filePathAndName - 文件路径
     * @param fileContent - 文件内容
     */
    public static void writeFile(String filePathAndName, String fileContent) {
        try {
            File file = new File(filePathAndName);
            if (!file.exists()) {
                file.createNewFile();
            }
            OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            BufferedWriter bufWriter = new BufferedWriter(writer);
            bufWriter.write(fileContent);
            bufWriter.close();
        } catch (IOException e) {
            System.out.println("写文件内容操作出错!");
            e.printStackTrace();
        }
    }

}
